<template>
  <div class="page-container">
    <el-card class="content-container">
      <div class="toolbar">
        <div class="toolbar-left">
          <h3>购物车管理</h3>
        </div>
        <div class="toolbar-right">
          <el-button type="danger" :disabled="selectedRows.length===0" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.yonghuName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.nongchanpinName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="(rows)=>selectedRows=rows"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="yonghuName" label="用户" />
        <el-table-column prop="nongchanpinName" label="商品名称" />
        <el-table-column prop="buyNumber" label="数量" width="100" />
        <el-table-column prop="nongchanpinNewMoney" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.nongchanpinNewMoney }}
          </template>
        </el-table-column>
        <el-table-column label="小计" width="120">
          <template #default="scope">
            ¥{{ (scope.row.buyNumber * scope.row.nongchanpinNewMoney).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="加入时间" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const instance = getCurrentInstance()
const http = instance?.proxy?.$http

// 响应式数据
const loading = ref(false)
const tableData = ref([])
let selectedRows = ref([])

const searchForm = reactive({
  yonghuName: '',
  nongchanpinName: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 方法
const loadData = async () => {
  if (!http) {
    ElMessage.error('系统初始化失败，请刷新页面重试')
    return
  }
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.size,
      ...searchForm
    }

    const res = await http({
      url: '/cart/page',
      method: 'get',
      params
    })

    if (res.code === 0) {
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '加载购物车数据失败')
    }
  } catch (e) {
    console.error('加载购物车数据失败', e)
    ElMessage.error('加载购物车数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

const handleBatchDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) return
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条购物车记录吗？`,
      '批量删除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    const ids = selectedRows.value.map(r => r.id)
    const res = await http({ url: '/cart/delete', method: 'post', data: { ids } })
    if (res.code === 0) {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('批量删除失败', e)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.yonghuName}"的购物车记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await http({
      url: '/cart/delete',
      method: 'post',
      data: { ids: [row.id] }
    })

    if (res.code === 0) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除购物车记录失败', e)
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/index.scss';
</style>
